package cn.tedu.smartos.family_user.service.impl;

import cn.tedu.smartos.base.exception.ServiceException;
import cn.tedu.smartos.base.response.StatusCode;
import cn.tedu.smartos.family_user.mapper.FamilyUserMapper;
import cn.tedu.smartos.family_user.pojo.dto.FamilyUserUpdateParam;
import cn.tedu.smartos.family_user.pojo.dto.PasswordUpdateParam;
import cn.tedu.smartos.family_user.pojo.vo.FamilyUserVO;
import cn.tedu.smartos.family_user.service.FamilyUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class FamilyUserServiceImpl implements FamilyUserService {
    @Autowired
    private FamilyUserMapper familyUserMapper;

    @Override
    public FamilyUserVO getFamilyUserInfo(Long userId) {
        log.debug("获取家属信息: userId={}", userId);
        FamilyUserVO familyInfo = familyUserMapper.selectById(userId);
        if (familyInfo == null) {
            throw new ServiceException(StatusCode.USER_NOT_EXIT);
        }
        return familyInfo;
    }
    @Override
    public void updatePassword(PasswordUpdateParam passwordParam) {
        log.debug("修改密码: {}", passwordParam);
        // 验证用户ID是否存在
        if (passwordParam.getUserId() == null) {
            throw new ServiceException(StatusCode.USER_NOT_EXIT, "用户ID不能为空");
        }
        // 验证旧密码
        FamilyUserVO user = familyUserMapper.selectById(passwordParam.getUserId());
        if (user == null) {
            throw new ServiceException(StatusCode.USER_NOT_EXIT);
        }
        if (passwordParam.getOldPassword() == null || user.getPassword() == null
                || !passwordParam.getOldPassword().equals(user.getPassword())) {
            throw new ServiceException(StatusCode.USERNAME_OR_PASSWORD_ERROR);
        }


        int rows = familyUserMapper.updatePassword(passwordParam);
        if (rows != 1) {
            throw new ServiceException(StatusCode.FAILED, "密码更新失败");
        }
    }

    @Override
    public void updateAvatar(Long userId, String avatarUrl) {
        log.debug("更新头像: userId={}, avatarUrl={}", userId, avatarUrl);
        int rows = familyUserMapper.updateAvatar(userId, avatarUrl);
        if (rows != 1) {
            throw new ServiceException(StatusCode.FAILED, "头像更新失败");
        }
    }

    @Override
    public void update(FamilyUserUpdateParam updateParam) {
        log.debug("更新家属信息: {}", updateParam);
        // 新增参数校验
        if (updateParam.getUserId() == null) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "非法请求，用户ID不能为空");
        }
        int rows = familyUserMapper.update(updateParam);
        if (rows != 1) {
            throw new ServiceException(StatusCode.FAILED, "信息更新失败");
        }
    }


}